<script type="text/javascript">
//定义产品ID
var fchrProductId = ''
//添加行
var trCount = ${salesOrderInstance?.salesOrderDetails?.size()?:0}
	trCount -=1
    //如果行数大于1，则不允许修改行业和项目
    if(trCount > -1) {
        $('[name="industryInput"]').attr("readonly", true)
        $('[name="project"]').attr("readonly", true)
    }
//添加行
function addOrderDetail(){
    //没有产品ID，返回
	if($("#searchProductId").val() == ''){
		return false;
	}
    fchrProductId = $("#searchProductId").val()
    $("#searchProductId").val('')
    //锁定页面
    $.blockUI();
    //根据ID取产品信息
    $.ajax({
        url: "${createLink(controller:'salesOrderAjax', action: 'productProperty224')}",
        data: { 
           dealerId: $("#dealer\\.id").val()
           , project : $("#project").val()
           , serialNumber: $("#searchProductNumber").val() 
        },
        dataType: "json",
        type: "POST",
        success: productPropertyCallback
    });
}
//根据返回的产品信息生成新的行
function productPropertyCallback(data){
    //解锁页面
    $.unblockUI();
    //行数加1
	trCount ++
    //当trCount大于-1时，锁定行业，项目
    if(trCount > -1) {
        $('[name="industryInput"]').attr("readonly", true)
        $('[name="project"]').attr("readonly", true)
    }    
	var rowid = trCount + 1
    //达到最大行数
	if(rowid > 99){
		alert("max row is 100");
		return false;
	}
    //隔行变色
	var css = (trCount % 2 == 0)?"odd":"even";
    //价格
	var price = $("#searchProductPrice").html()
    //标准折扣
	var discount = data.discount
    //序号
	var serialNumber = (rowid < 10) ? '0' + rowid : '' + rowid
    //交付周期
	var deliveryCycle = data.delivery

	var parent_contract_detail_id = ""
	var parent_contract_detail_serailNumber = ""
	var parent_special_discount = 0

	if($(data.contractDetails).size() > 0){
		parent_contract_detail_id = data.contractDetails[0].id
		parent_contract_detail_serailNumber = data.contractDetails[0].serialNumber
		parent_special_discount = data.contractDetails[0].specialDiscount
	}
	var parent_final_discount = discount.mul( parseFloat(1, 10).sub( parent_special_discount ) )
		
    //增加行
	$("#salesOrderDetailList").append(
		$("<tr class='prop "+css+"' ></tr>").append(//tr
			$("<td name='serialNumber'><span>"+serialNumber+"</span></td>").append(//serial number
				$('<input name="salesOrderDetails['+trCount+'].serialNumber" value="'+serialNumber+'" type="hidden" />')
			).append(//br
				$("<br/>")
			).append(//delete
				$('<a href="#addSalesOrderDetailLink" delete="delete">${message(code: 'default.button.delete', default: 'Delete')}</a>').bind('click', myDeleteRow)
			)
		).append(//product.id
			$("<td name='product.id'></td>").append(
				$('<span>'+$("#searchProductNumber").val()+'</span>')
			).append(
				$('<input name="salesOrderDetails['+trCount+'].product.id" value="'+fchrProductId+'" type="hidden" />')					
			)
		).append(//product.name
			$("<td name='product.name'></td>").append(
				$('<span>'+$("#searchProductName").html()+'</span>')
			)
		).append(//product.standard
			$("<td name='product.standard'></td>").append(
				$('<span>'+$("#searchProductStandard").html()+'</span>')
			)
		).append(//category
			$("<td name='category'></td>").append(
				$('<span>'+(data.category?data.category:'')+'</span>')
			)
		).append(//price
			$("<td name='price' class='value number'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].price" value="'+$.formatNumber(price, "###,##0.000000")+'" readonly="readonly" />')
			).append(
                $('<span>('+data.allowZeroPrice+')</span>')
            )
		).append(//discount
			$("<td name='discount' class='value number'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].discount" value="'+discount.toFixed(4) +'"  readonly="readonly" style="width:60px;" />')					
			)
		).append(//quantity
			$("<td name='quantity' class='value number'></td>").append(
				$("<input name='salesOrderDetails["+trCount+"].quantity' value='0' type='text' >").keypress(myKeypress).focus(myFocus).blur(myBlur).bind('paste', myPaste).change(myChange)
			)
		).append(//delivery limitation
			$("<td name='deliveryLimitation'></td>").append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation" value="date.struct" />'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_year" value=""/>'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_month" value=""/>'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_day" value=""/>'
			).append(
				$("<input target='salesOrderDetails["+trCount+"].deliveryLimitation' datepicker='datepicker' type='text' style='width:80px;'>").datepicker({
					  dateFormat: 'yy-mm-dd'
					, minDate: new Date(new Date().getTime() + deliveryCycle * 24 * 60 * 60 * 1000)
					, onClose: function(dateText, inst) {
						$('[name="'+$(this).attr('target') + '_year"]').val(inst.selectedYear)
						$('[name="'+$(this).attr('target') + '_month"]').val(inst.selectedMonth + 1)
						$('[name="'+$(this).attr('target') + '_day"]').val(inst.selectedDay)
					}
				}).attr("readonly", true)
			).append(
				$("<span>"+deliveryCycle+"</span>")
			)
		).append(//amount
			$("<td name='amount' class='value number'>0.0000</td>")
		).append(//contract detail
			$("<td name='contractDetail.id'></td>").append(
				$("<span>"+parent_contract_detail_serailNumber+"</span>")
			).append(
				$("<input type='hidden' name='salesOrderDetails["+trCount+"].contractDetail.id' value='"+parent_contract_detail_id+"'/>")
			)
		).append(//special discount
			$("<td name='specialDiscount' class='value number'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].specialDiscount" value="'+parent_special_discount.toFixed(4)+'"  readonly="readonly" style="width:60px;" />')					
			).append(
                $('<span>('+data.allowSpecialDiscount+')</span>')
            )
		).append(//special amount
			$("<td name='specialAmount' class='value number'>0.0000</td>")
		).append(//final discount
			$("<td name='finalDiscount' class='value number'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].finalDiscount" value="'+parent_final_discount.toFixed(4) +'"  readonly="readonly" style="width:60px;" />')					
			)
		).append(//final amount
			$("<td name='finalAmount' class='value number'>0.0000</td>")
		)
	)
    //重置搜索框
    initSearchProduct();
    $("#searchProductNumber").focus();    
}
// on quantity input element onblur
function myBlur(){
	var v = parseInt($.formatNumber(this.value, "##0.00"), 10);
		v = isNaN(v) ? $(this).data("before") : v;
	//set value
	this.value = $.formatNumber(v, "###,##0.00")
		
	//get value--parent quantity
	var parent_quantity = v
        parent_quantity = parseFloat(parent_quantity, 10)

	//get parent tr
	var parent_tr = $(this).parent().parent();
	
	//get parent price
	var parent_price = parent_tr.children("td[name=price]").children(":first-child").val()
		parent_price = $.formatNumber(parent_price, "#0.000000")
        parent_price = parseFloat(parent_price, 10)
	
	//get parent disocunt
	var parent_discount = parent_tr.children("td[name=discount]").children(":first-child").val()
		parent_discount = $.formatNumber(parent_discount, "#0.0000")
        parent_discount = parseFloat(parent_discount, 10)
	//get parent special disocunt
	var parent_special_discount = parent_tr.children("td[name=specialDiscount]").children(":first-child").val()
		parent_special_discount = $.formatNumber(parent_special_discount, "#0.0000")
        parent_special_discount = parseFloat(parent_special_discount, 10)
	//get parent final disocunt
	var parent_final_discount = parent_tr.children("td[name=finalDiscount]").children(":first-child").val()
		parent_final_discount = $.formatNumber(parent_final_discount, "#0.0000")
        parent_final_discount = parseFloat(parent_final_discount, 10)
	//parent amount
	var parent_amount_td = parent_tr.children("td[name=amount]")
		//get old row amount
		var old_row_amount = parent_amount_td.html()
			old_row_amount = $.formatNumber(old_row_amount, "##0.0000")
            old_row_amount = parseFloat(old_row_amount, 10)
		//calculate new row amount
		var new_row_amount = parent_price.mul( parent_discount).mul(parent_quantity)
		//set row amount
		parent_amount_td.html($.formatNumber(new_row_amount, "###,##0.0000"))
	//parent special amount
	var parent_special_amount_td = parent_tr.children("td[name=specialAmount]")
		//get old row amount
		var old_row_special_amount = parent_special_amount_td.html()
			old_row_special_amount = $.formatNumber(old_row_special_amount, "##0.0000")
            old_row_special_amount = parseFloat(old_row_special_amount, 10)
		//calculate new row amount
		var new_row_special_amount = parent_price.mul( parent_discount ).mul( parent_special_discount ).mul( parent_quantity )
		//set row special amount
		parent_special_amount_td.html($.formatNumber(new_row_special_amount, "###,##0.0000"))
	//parent final amount
	var parent_final_amount_td = parent_tr.children("td[name=finalAmount]")
		//get old row amount
		var old_row_final_amount = parent_final_amount_td.html()
			old_row_final_amount = $.formatNumber(old_row_final_amount, "##0.0000")
            old_row_final_amount = parseFloat(old_row_final_amount, 10)
		//calculate new row amount
		var new_row_final_amount = parent_price.mul( parent_discount ).mul( (parseFloat(1, 10).sub( parent_special_discount )) ).mul( parent_quantity )
		//set row special amount
		parent_final_amount_td.html($.formatNumber(new_row_final_amount, "###,##0.0000"))

	//total amount
	var total_amount_td = $("td[name=totalAmount]")
		//get total amount
		var old_total_amount = total_amount_td.html()
			old_total_amount = $.formatNumber(old_total_amount, "##0.0000")
            old_total_amount = parseFloat(old_total_amount, 10)
		//calculate new total amount
		var new_total_amount = old_total_amount.sub(  old_row_amount ).add( new_row_amount )

		//set total amount
		total_amount_td.html($.formatNumber(new_total_amount, "###,##0.0000"))
		
	//total special amount
	var total_special_amount_td = $("td[name=totalSpecialAmount]")
		//get total amount
		var old_total_special_amount = total_special_amount_td.html()
			old_total_special_amount = $.formatNumber(old_total_special_amount, "##0.0000")
            old_total_special_amount = parseFloat(old_total_special_amount, 10)
		//calculate new total amount
		var new_total_special_amount = old_total_special_amount.sub( old_row_special_amount ).add( new_row_special_amount )

		//set total amount
		total_special_amount_td.html($.formatNumber(new_total_special_amount, "###,##0.0000"))
	
	//total final amount
	var total_final_amount_td = $("td[name=totalFinalAmount]")
		//get total amount
		var old_total_final_amount = total_final_amount_td.html()
			old_total_final_amount = $.formatNumber(old_total_final_amount, "##0.0000")
            old_total_final_amount = parseFloat(old_total_final_amount, 10)
		//calculate new total amount
		var new_total_final_amount = old_total_final_amount.sub( old_row_final_amount ).add( new_row_final_amount )

		//set total amount
		total_final_amount_td.html($.formatNumber(new_total_final_amount, "###,##0.0000"))
}
function myDeleteRow(){
    if($(this).parent().parent().parent().attr("id") != 'salesOrderDetailList'){
        return false;
    }
	if(!confirm('Delete!')){
		return false;
	}
	//get parent tr
	var parent_tr = $(this).parent().parent();
	//get childs tr parent property
	var childs_tr_parent = parent_tr.attr("childs")
	
	//get row amount
	var amount = $(parent_tr).children("td[name=amount]").html().trim()
		amount = $.formatNumber(amount, "#0.0000")
        amount = parseFloat(amount, 10)
		
	//get row special amount
	var special_amount = $(parent_tr).children("td[name=specialAmount]").html().trim()
		special_amount = $.formatNumber(special_amount, "#0.0000")
        special_amount = parseFloat(special_amount, 10)

	//get row final amount
	var final_amount = $(parent_tr).children("td[name=finalAmount]").html().trim()
		final_amount = $.formatNumber(final_amount, "#0.0000")
        final_amount = parseFloat(final_amount, 10)
		
	var total_amount_td = $("td[name=totalAmount]")
	var total_special_amount_td = $("td[name=totalSpecialAmount]")
	var total_final_amount_td = $("td[name=totalFinalAmount]")
		
	//get total amount
	var old_total_amount = total_amount_td.html()
		old_total_amount = $.formatNumber(old_total_amount, "##0.0000")
        old_total_amount = parseFloat(old_total_amount, 10)
		
	//get special total amount
	var old_total_special_amount = total_special_amount_td.html()
		old_total_special_amount = $.formatNumber(old_total_special_amount, "##0.0000")
        old_total_special_amount = parseFloat(old_total_special_amount, 10)

	//get total final amount
	var old_total_final_amount = total_final_amount_td.html()
		old_total_final_amount = $.formatNumber(old_total_final_amount, "##0.0000")
        old_total_final_amount = parseFloat(old_total_final_amount, 10)
		
	//calculate new total amount
	var new_total_amount = old_total_amount.sub( amount )
	//calculate new total special amount
	var new_total_special_amount = old_total_special_amount.sub( special_amount )
	//calculate new total final amount
	var new_total_final_amount = old_total_final_amount.sub( final_amount )

	//set total amount
	total_amount_td.html($.formatNumber(new_total_amount, "###,##0.0000"))
	//set total special amount
	total_special_amount_td.html($.formatNumber(new_total_special_amount, "###,##0.0000"))
	//set total final amount
	total_final_amount_td.html($.formatNumber(new_total_final_amount, "###,##0.0000"))
	
	$(parent_tr).remove()

	refreshSerialNumber();
}

function refreshSerialNumber(){
	var rowindex = -1
	//get table all parent row
	$("#salesOrderDetailList > tr").each(function(){
		rowindex ++;
		var new_serialNumber = (rowindex + 1 < 10)? "0" + (rowindex + 1) : "" + (rowindex + 1);
		//update tr childs
		$(this).children("td").each(function(){
			switch($(this).attr('name')){
				case 'serialNumber':
					$(this).children(":nth-child(1)").html(new_serialNumber);
					$(this).children(":nth-child(2)").val(new_serialNumber);
				case 'product.id':
				case 'price':
				case 'discount':
				case 'contractDetail.id':
				case 'specialDiscount':
				case 'finalDiscount':
				case 'quantity':
				case 'deliveryLimitation':
				case '':
					$(this).children("input").each(function(){
						var old_name=$(this).attr("name")||$(this).attr("target");
						var begin = old_name.indexOf("[", 0);
						var end = old_name.indexOf("]", begin);
						var new_name = old_name.substring(0, begin + 1) + rowindex + old_name.substr(end);
						//$(this).attr("name", new_name).attr("id", new_name);
						if($(this).attr("name")){$(this).attr("name", new_name)}
						if($(this).attr("id")){$(this).attr("id", new_name)}
						if($(this).attr("target")){
							var deliveryCycle = $(this).parent().children(":last-child").html().replace(/\r\n/g, "").trim();
							
							$(this).attr("target", new_name).datepicker("destroy").datepicker({
								dateFormat: 'yy-mm-dd'
								, minDate: new Date(new Date().getTime() + deliveryCycle * 24 * 60 * 60 * 1000)
								, onClose: function(dateText, inst) {
									$('[name="'+$(this).attr('target') + '_year"]').val(inst.selectedYear)
									$('[name="'+$(this).attr('target') + '_month"]').val(inst.selectedMonth + 1)
									$('[name="'+$(this).attr('target') + '_day"]').val(inst.selectedDay)
								}
							})
						}
					})
					break;
			}

		})
	})
	trCount = rowindex;
    //当trCount大于-1时，锁定行业，项目
    if(trCount <= 0){
        $('[name="industryInput"]').attr("readonly", false)
        $('[name="project"]').attr("readonly", false)
    }
}
$(function(){
	//project list auto complete
	$("#project").autocomplete({
		minLength: 0,
		source: function(request, response) {
			$.ajax({
			    url: "${createLink(controller:'salesOrderAjax', action: 'projectList224')}",
			    data: { dealer: $("#dealer\\.id").val(), industry: $("#industry\\.id").val(), term: request.term },
			    dataType: "json",
			    type: "POST",
			    success: function( data ) {
			        response( $.map( data, function( item ) {
			            return {
			                  project : item[0]
			            	, value: item[0]
			                , label: item[0] + '|' + item[1]
			            }
			        }));
			    }
			});
		},
		select: function( event, ui ) {
			$("#project").val(ui.item.project);
		}
	});
	//trigger parent row quantity onblur
	$("#salesOrderDetailList tr[childs] input[name$=quantity]").each(function(){
		
		$(this).trigger('blur');
	})
})
</script>
